package cn.bandeqing.userWallet.service.impl;

import cn.bandeqing.frame.exception.CodeException;
import cn.bandeqing.userWalletRecord.entity.UserWalletRecord;
import cn.bandeqing.userWalletRecord.entity.UwrType;
import cn.bandeqing.userWalletRecord.service.IUserWalletRecordService;
import cn.bandeqing.workerWallet.entity.WorkerWallet;
import cn.bandeqing.workerWalletRecord.entity.WorkerWalletRecord;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import cn.bandeqing.userWallet.entity.UserWallet;
import cn.bandeqing.userWallet.mapper.UserWalletMapper;
import cn.bandeqing.userWallet.service.IUserWalletService;
import jakarta.annotation.Resource;
import org.dromara.hutool.core.lang.Assert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户余额 服务层实现。
 *
 * @author fugui
 * @since 2024-01-28
 */
@Service
public class UserWalletServiceImpl extends ServiceImpl<UserWalletMapper, UserWallet> implements IUserWalletService {

    @Resource
    private IUserWalletRecordService userWalletRecordService;

    @Override
    @Transactional
    public void changeBalance(Long usId, String usNickName, Double money, String desc, Long ocId, Long orderId, UwrType uwrType) {

        UserWallet uw = getById(usId);

        Double before = uw.getUsBalance();
        Double after = before + money;

        boolean b = updateById(UserWallet.builder()
                .usId(usId)
                .usBalance(after)
                .build());
        Assert.isTrue(b, () -> new CodeException("用户钱包变动失败"));

        boolean save = userWalletRecordService.save(UserWalletRecord.builder()
                .usId(usId)
                .usNickName(usNickName)
                .orderId(orderId)
                .uwrType(uwrType)
                .uwrDesc(desc)
                .beforeMoney(before)
                .changeMoney(money)
                .afterMoney(after)
                .ocId(ocId)
                .build());
        Assert.isTrue(save, () -> new CodeException("用户钱包记录保存失败"));
    }

}
